package com.icss.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;


public class DB {

	//数据源
	private static DataSource dataSource = null;

	//上下文中的地址
	private static final String DS_CONTEXT = "java:comp/env/jdbc/etcDS";

	//初始化数据源，通过该方法达到数据源单例的效果
	private static void initDataSource() {
		if (null == dataSource) {
			InitialContext ctx;
			try {
				ctx = new InitialContext();
				dataSource = (DataSource) ctx.lookup(DS_CONTEXT);
			} catch (NamingException e) {
				e.printStackTrace();
			}
		}
	}

	//获得数据库连接
	public static Connection getConnection() {

		Connection connection = null;
		if (null == dataSource) {
			initDataSource();
		}

		try {
			connection = dataSource.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return connection;
	}
	
	public static Connection getDriverConnection() {
		Connection connection = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbo","dbo","admin");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return connection;
	}

}
